package cn.xmall.resolvers;

import cn.xmall.commons.utils.CookieUtils;
import cn.xmall.models.User;
import cn.xmall.services.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpServletRequest;

@Component
public class CurrentUserArgumentResolvers implements WebArgumentResolver {

    private static final Logger logger = LoggerFactory.getLogger(CurrentUserArgumentResolvers.class);
    @Autowired
    UserService userService;

    private final String WX_HEADER="WXSP_XMALL_MOBILE";

    private final String WX_TOKEN_KEY="XMALL-Token";

    @Override
    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {
        if(methodParameter.getParameterType()!=null
                &&  methodParameter.getParameterType().equals(User.class)){
            HttpServletRequest httpServletRequest=webRequest.getNativeRequest(HttpServletRequest.class);

            String userAgent=httpServletRequest.getHeader("user-agent");
            String referer=httpServletRequest.getHeader("referer");
            String reqAgent=httpServletRequest.getHeader("request-agent");

            logger.debug("referer:{}",referer);
            logger.debug("user-agent:{}",userAgent);
            logger.debug("request-agent:{}",reqAgent);

            String userSessionID="";
            if(userAgent.equals(WX_HEADER)){
                userSessionID=httpServletRequest.getHeader(WX_TOKEN_KEY);
                logger.debug(userSessionID);
            }else {
                userSessionID=CookieUtils.getCookieValue(httpServletRequest,"XMALL_SESSION_ID");
            }

            User user=null;
            if(StringUtils.hasText(userSessionID)){
                user=userService.getLoggedInUserByToken(userSessionID);
            }


            return (Object)user;
        }
        return UNRESOLVED;
    }
}
